//
//  AddCarDriverVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/12/5.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AddCarDriverVC.h"
#import "TopBackView.h"
#import "LicenseVC.h"
#import "Common.h"
#import "TimePickerView.h"
#import "WKProgressHUD.h"


@interface AddCarDriverVC ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField *nameField;//姓名
@property (nonatomic,strong) UITextField *phoneField;//电话
@property (nonatomic,strong) UITextField *idField;//身份证号
@property (nonatomic,strong) UITextField *numberField;//驾照初领时间
@property (nonatomic,strong) UIButton *licenseButton;//驾照类型
@property (nonatomic,strong) UIView *backgroundView;
@property (nonatomic,retain) TimePickerView *timeView;
@property (nonatomic) int currentTextFieldIndex;
@property (nonatomic,strong) NSMutableArray *textFieldArray;

@property (nonatomic,strong) NSMutableDictionary *postDic;

@property (nonatomic) BOOL show;


@end

@implementation AddCarDriverVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"我的司机"];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = WhiteColor;
    self.textFieldArray = [NSMutableArray array];
    self.postDic = [NSMutableDictionary dictionary];
    _show = NO;
    [self initTextField];

    [self initPostDic];
    [self initSubViews];
    
    
}


-(void)initPostDic
{
    //新增
    if (self.name == nil) {
        
        [self.postDic setObject:@"" forKey:@"realName"];
        [self.postDic setObject:@"" forKey:@"phone"];
        [self.postDic setObject:@"" forKey:@"idCard"];
        [self.postDic setObject:@"" forKey:@"licenceIds"];
//        [self.postDic setObject:@"" forKey:@"receiveDate"];
        
        
        
        NSDate *date = [NSDate date];
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        
        NSInteger interval = [zone secondsFromGMTForDate: date];
        
        NSDate *localeDate = [date dateByAddingTimeInterval: interval];
        NSDateFormatter *forma = [[NSDateFormatter alloc]init];
        
        [forma setDateFormat:@"YYYY-MM-dd"];
        NSString *str = [forma stringFromDate:localeDate];
        NSArray *arr = [str componentsSeparatedByString:@" "];
        
        //初始化上传日期
        [self.postDic setObject:arr[0]  forKey:@"receiveDate"];

        
    } else {
        //编辑
        
        self.nameField.text = self.name;
        self.phoneField.text = self.phone;
        self.idField.text = self.identify;
        self.numberField.text = self.recieveDate;
        
        
        [self.postDic setObject:self.name forKey:@"realName"];
        [self.postDic setObject:self.phone forKey:@"phone"];
        [self.postDic setObject:self.identify forKey:@"idCard"];
        [self.postDic setObject:@"" forKey:@"licenceIds"];
        [self.postDic setObject:self.recieveDate forKey:@"receiveDate"];
        [self.postDic setObject:self.dUserId forKey:@"dUserId"];
        [self.postDic setObject:self.sUserId forKey:@"sUserId"];
        
        [self getLicenseId];
        
    }
}

-(void)initTextField
{
    self.nameField = [[UITextField alloc]init];
    self.nameField.keyboardType = UIKeyboardTypeDefault;
    
    self.phoneField = [[UITextField alloc]init];
    self.phoneField.keyboardType = UIKeyboardTypePhonePad;
    
    self.idField = [[UITextField alloc]init];
    self.idField.keyboardType = UIKeyboardTypeDefault;

    self.numberField = [[UITextField alloc]init];
    self.numberField.keyboardType = UIKeyboardTypeDefault;
    
    NSDate * date = [NSDate date];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    //指定输出的格式   这里格式必须是和上面定义字符串的格式相同，否则输出空
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeString= [formatter stringFromDate:date];
    
//    NSFormatter
    
    self.numberField.text = [NSString stringWithFormat:@"%@", timeString];
    
    
    [self initToolBar];

}

-(void)initToolBar
{
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0,screenWidth, 35 * kHeight)];
    toolBar.backgroundColor = Color_RGB(248, 230, 208, 1);
    //    [self.view addSubview:toolBar];
    
    UIBarButtonItem *btnPlace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *lastButton = [[UIBarButtonItem alloc]initWithTitle:@"上一个" style:UIBarButtonItemStylePlain target:self action:@selector(lastOneFirstResponser:)];
    
    [lastButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    
    UIBarButtonItem *nextButton = [[UIBarButtonItem alloc]initWithTitle:@"下一个" style:UIBarButtonItemStylePlain target:self action:@selector(nextOneFirstResponder:)];
    
    [nextButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(keyBoardExit:)];
    
    [doneButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    NSArray *itemsArray = @[lastButton,nextButton,btnPlace,doneButton];
    toolBar.items = itemsArray;
    
    self.nameField.inputAccessoryView = toolBar;
    self.phoneField.inputAccessoryView = toolBar;
    self.idField.inputAccessoryView = toolBar;
    self.numberField.inputAccessoryView = toolBar;
    
        self.textFieldArray = [NSMutableArray arrayWithObjects:self.nameField,self.phoneField,self.idField,self.numberField,nil];

}

-(void)nextOneFirstResponder:(UIBarButtonItem *)sender
{
    if (_currentTextFieldIndex + 1 <= self.textFieldArray.count - 1) {
        UITextField *textField = self.textFieldArray[_currentTextFieldIndex + 1];
        
        if (textField == self.numberField) {
            [textField resignFirstResponder];

            if (_show) {
                
            } else {
                [self choiceDate];

            }

        } else {
            [textField becomeFirstResponder];

        }
        
    }
}

-(void)lastOneFirstResponser:(UIBarButtonItem *)sender
{
    if (_currentTextFieldIndex - 1 >= 0) {
        UITextField *textField = self.textFieldArray[_currentTextFieldIndex - 1];
        if (textField == self.numberField) {
            
            [textField resignFirstResponder];
            [self choiceDate];
            
        } else {
            [textField becomeFirstResponder];
            
        }    }
}

-(void)keyBoardExit:(UIBarButtonItem *)sender
{
    [self.view endEditing:YES];
}

#pragma mark UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
    if (textField == self.nameField) {
        _currentTextFieldIndex = 0;
        
    }
    
    if (textField == self.phoneField) {
        _currentTextFieldIndex = 1;

    }
    
    if (textField == self.idField) {
        _currentTextFieldIndex = 2;

        
    }
    
    if (textField != self.numberField) {
        
        [textField addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];

    }
    

    
    if (textField == self.numberField) {
        _currentTextFieldIndex = 3;
    
//        [self choiceDate];
        
    }
    
}


-(void)valueChanged:(UITextField *)textfield
{
    if (_currentTextFieldIndex == 0) {
        [self.postDic setObject:self.nameField.text forKey:@"realName"];

    }
    
    if (_currentTextFieldIndex == 1) {
        [self.postDic setObject:self.phoneField.text forKey:@"phone"];

    }
    
    if (_currentTextFieldIndex == 2) {
        [self.postDic setObject:self.idField.text forKey:@"idCard"];

    }
    

}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
   
        [textField resignFirstResponder];
        return YES;

}



-(void)initSubViews
{
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, cellHeight)];
    topView.backgroundColor = GrayColor;
    [self.view addSubview:topView];
    
    UILabel *titleL =   [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 200, cellHeight)];
    titleL.text = @"录入司机信息";
    titleL.font = Font(14);
    titleL.textColor = carScrollColor;
    [topView addSubview:titleL];
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, cellHeight - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [topView addSubview:lineL];
    
    UIView *firstV = [self backViewWithTitle:@"姓名" andObject:self.nameField andInteger:1];
    [self.view addSubview:firstV];
  
    
    UIView *secondV = [self backViewWithTitle:@"电话" andObject:self.phoneField andInteger:2];
    [self.view addSubview:secondV];
  
    
    UIView *thirdV = [self backViewWithTitle:@"身份证号" andObject:self.idField andInteger:3];
    [self.view addSubview:thirdV];
    

    
    UIView *fourthV = [self backViewWithTitle:@"驾照初领时间" andObject:self.numberField andInteger:4];
    [self.view addSubview:fourthV];
    
    UIButton *timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    timeButton.frame = CGRectMake(0, 0, self.numberField.frame.size.width, self.numberField.frame.size.height);
    [self.numberField addSubview:timeButton];
    [timeButton addTarget:self action:@selector(choiceDate) forControlEvents:UIControlEventTouchUpInside];
    

    
    self.licenseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIView *fifthV = [self backViewWithTitle:@"准驾类型" andButton:self.licenseButton andInteger:5];
    [self.view addSubview:fifthV];
    [self.licenseButton addTarget:self action:@selector(licenseButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.license != nil) {
        [self.licenseButton setTitle:self.license forState:UIControlStateNormal];
    }

    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmButton.frame = CGRectMake(20, CGRectGetMaxY(fifthV.frame) + 60, screenWidth - 40, Button_height);
    confirmButton.titleLabel.font = Font(15);
    [confirmButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    confirmButton.backgroundColor = YellowColor;
    [confirmButton setTitle:@"确 定" forState:UIControlStateNormal];
//    confirmButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.view addSubview:confirmButton];
    [confirmButton addTarget:self action:@selector(confirmButtonAction) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.layer.cornerRadius = 5;
    
}


-(UIView *)backViewWithTitle:(NSString *)title andObject:(UITextField *)field andInteger:(NSInteger)integer
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, cellHeight * integer + 64, screenWidth, cellHeight)];
    view.backgroundColor = WhiteColor;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 120, cellHeight)];
    label.text = title;
    label.font = Font(14);
    label.textColor = carScrollColor;
    [view addSubview:label];
    
    field.frame = CGRectMake(CGRectGetMaxX(label.frame), 0, screenWidth - 153, cellHeight);
    field.textAlignment = NSTextAlignmentRight;
    field.textColor = carScrollColor;
    field.font = Font(14);
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view addSubview:field];
    field.delegate = self;
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, cellHeight - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [view addSubview:lineL];
    
    return view;
}


-(UIView *)backViewWithTitle:(NSString *)title andButton:(UIButton *)button andInteger:(NSInteger)integer
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, cellHeight * integer + 64, screenWidth, cellHeight)];
    view.backgroundColor = WhiteColor;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100, cellHeight)];
    label.text = title;
    label.font = Font(14);
    label.textColor = carScrollColor;
    [view addSubview:label];
    
    button.frame = CGRectMake(CGRectGetMaxX(label.frame), 0, screenWidth - 133, cellHeight);
    button.titleLabel.font = Font(14);
    [button setTitleColor:carScrollColor forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [view addSubview:button];
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, cellHeight - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [view addSubview:lineL];
    
    return view;
}

-(void)confirmButtonAction
{
    
    if (self.name != nil) {
        //编辑
        
        NSArray *arr = [self.postDic allValues];
        
        if ([arr containsObject:@""]) {
            [WKProgressHUD popMessage:@"请将信息补充完整" inView:self.view duration:1.5 animated:YES];
            
        }else if (![self IsPhoneNumber:self.postDic[@"phone"]]){
            [WKProgressHUD popMessage:@"请填写正确手机号" inView:self.view duration:1.5 animated:YES];
            
            
        } else if (![self IsIdentityCard:self.postDic[@"idCard"]]){
            [WKProgressHUD popMessage:@"请填写正确身份证号" inView:self.view duration:1.5 animated:YES];
            
        } else {

//        NSString *urlString = [NSString stringWithFormat:@"%@sub/editdriver",Main_interface];
        Common *c = [[Common alloc]init];
        
        
        [c afPostRequestWithUrlString:sub_editdriver parms:self.postDic finishedBlock:^(id responseObj) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            if ([dic[@"success"] boolValue]) {
                
                //延迟执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                        [self.navigationController popViewControllerAnimated:YES];
                    
                });
                
            }
            
            
        } failedBlock:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
        }];
        }
        
    } else {
    //新增
    
    NSArray *arr = [self.postDic allValues];
    if ([arr containsObject:@""]) {
        [WKProgressHUD popMessage:@"请将信息补充完整" inView:self.view duration:1.5 animated:YES];

    } else if (![self IsPhoneNumber:self.postDic[@"phone"]]){
        [WKProgressHUD popMessage:@"请填写正确手机号" inView:self.view duration:1.5 animated:YES];

        
    } else if (![self IsIdentityCard:self.postDic[@"idCard"]]){
        [WKProgressHUD popMessage:@"请填写正确身份证号" inView:self.view duration:1.5 animated:YES];

    } else {
    
//    NSString *urlString = [NSString stringWithFormat:@"%@sub/adddriver",Main_interface];
    Common *c = [[Common alloc]init];
        
    [c afPostRequestWithUrlString:sub_adddriver parms:self.postDic finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
        
        if ([dic[@"success"] boolValue]) {
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            });
            
        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    }
    }
    
}


-(void)licenseButtonAction
{
    __weak typeof(self) weakSelf = self;
    LicenseVC *licenseV = [[LicenseVC alloc]init];
    if (self.dUserId != nil) {
        licenseV.did = self.dUserId;
    } else {
        licenseV.did = @"";
    }
    
    licenseV.callBack = ^(NSString *str,NSString *str1){
      
        [weakSelf.licenseButton setTitle:str1 forState:UIControlStateNormal];
        [weakSelf.postDic setObject:str forKey:@"licenceIds"];
        
    };
    
    [self.navigationController pushViewController:licenseV animated:YES];
}



-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 选择时间
-(void)choiceDate
{

//    [self textFieldDidEndEditing:self.numberField];
//    [self.numberField ];
    
    _show = YES;
    [self.view endEditing:YES];
//
    __weak typeof(self) weakSelf = self;
    
    self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    
    self.timeView = [[TimePickerView alloc]initWithFrame:CGRectMake(0, screenHeight, screenWidth, screenHeight)];
    
    self.timeView.value = self.numberField.text;
    self.timeView.datePicker.maximumDate = [NSDate date];

    self.timeView.backgroundColor = WhiteColor;
    self.timeView.callBack = ^(NSString *str){
        
        if (str == nil) {
            
            
        } else {
            [weakSelf.numberField setText:str];
            [weakSelf.postDic setObject:[weakSelf dateStringWith:str] forKey:@"receiveDate"];
        }
        
        
        [UIView animateWithDuration:0.4 animations:^{
            
            [weakSelf.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
            
            weakSelf.timeView.frame = CGRectMake(0, screenHeight  , screenWidth, 200);
            
        } completion:^(BOOL finished) {
            [weakSelf.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1]];
            _show = NO;
            [weakSelf.backgroundView removeFromSuperview];
        }];
    };
    
    //    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    
    
    [UIView animateWithDuration:0.4 animations:^{
        
        [weakSelf.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
        
        weakSelf.timeView.frame = CGRectMake(0, screenHeight - 200, screenWidth, 200);
        
        [window addSubview:weakSelf.backgroundView];
        [weakSelf.backgroundView addSubview:weakSelf.timeView];
        
    } completion:^(BOOL finished) {
        //        [self.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
        
    }];
    
}

//日期替换  2016年－12月－12日  2016-12-12
-(NSString *)dateStringWith:(NSString *)str
{
    
    str = [str stringByReplacingOccurrencesOfString:@"年" withString:@""];
    str =  [str stringByReplacingOccurrencesOfString:@"月" withString:@""];
    str =  [str stringByReplacingOccurrencesOfString:@"日" withString:@""];
    return  str;
    
}

#pragma mark 获取驾照id
-(void)getLicenseId
{
    NSMutableArray *arr = [NSMutableArray array];
    NSString *urlString = [NSString stringWithFormat:@"%@?duserid=%@",licensetype_list,self.dUserId];
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"data"] count] > 0) {
            for (int i = 0; i < [responseObj[@"data"] count]; i ++) {
                
                
                if ([responseObj[@"data"][i][@"isCheck"] boolValue]) {
                    [arr addObject:responseObj[@"data"][i][@"id"]];

                }
                
            }
        }
        
        
                NSString *str = [arr componentsJoinedByString:@","];
                [self.postDic setObject:str forKey:@"licenceIds"];

             
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}

//身份证验证
- (BOOL)IsIdentityCard:(NSString *)IDCardNumber
{
    if (IDCardNumber.length <= 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:IDCardNumber];
}
//手机号验证
- (BOOL)IsPhoneNumber:(NSString *)number
{
    NSString *phoneRegex1=@"1[34578]([0-9]){9}";
    NSPredicate *phoneTest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex1];
    return  [phoneTest1 evaluateWithObject:number];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
